import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:info_ca/bean/hostModel.dart';

import '../bean/aerticleList.dart';
import 'package:http/http.dart' as http;

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var articleList = [];
  final String host = HostModel.ipHost;
  void refreshArticleList() async {
    try {
      final response = await http.get(
        Uri.parse("http://$host/view/list"),
        headers: {
          'Authorization': 'Bearer',
        },
      ).timeout(const Duration(seconds: 30));
      if (response.statusCode == 200) {
        articleList.clear();
        final List Json = json.decode(response.body)['result']['list'];
        setState(() {
          articleList = Json;
        });
      }
    } catch (e) {
      print(e);
      throw Exception('Failed to load');
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refreshArticleList();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
        //导航栏的长度
        length: 3,
        child: Scaffold(
          appBar: buildAppBar(context),
          body: buildBodyWidget(context),
        ));
    ;
  }

  // 顶部导航栏
  PreferredSizeWidget buildAppBar(BuildContext context) {
    return AppBar(
      // title: const Text("AppBarDemoPage"),
      backgroundColor: Colors.white,
      elevation: 0,
      // centerTitle: true,
      toolbarHeight: 10,
      bottom: const TabBar(
        isScrollable: true, //可滚动
        indicatorColor: Color.fromARGB(0, 0, 0, 0), //指示器的颜色
        labelColor: Colors.black, //选中文字颜色
        unselectedLabelColor: Colors.grey, //未选中文字颜色
        // indicatorSize: TabBarIndicatorSize.label, //指示器与文字等宽
        labelStyle: TextStyle(fontSize: 25.0),
        unselectedLabelStyle: TextStyle(fontSize: 15.0),
        tabs: <Widget>[
          Tab(text: "关注"),
          Tab(text: "推荐"),
          Tab(text: "热门"),
        ],
      ),
    );
  }

  // 主体
  Widget buildBodyWidget(BuildContext context) {
    return TabBarView(
      children: <Widget>[
        Container(
            color: Colors.white,
            child: ListView.builder(
              itemCount: articleList.length,
              itemBuilder: (context, index) {
                final article = articleList[index];
                return buildRecommendWidget(context, article);
              },
            )),
        Container(
            color: Colors.white,
            child: ListView.builder(
              itemCount: articleList.length,
              itemBuilder: (context, index) {
                final article = articleList[index];
                return buildRecommendWidget(context, article);
              },
            )),
        Container(
            color: Colors.white,
            child: ListView.builder(
              itemCount: articleList.length,
              itemBuilder: (context, index) {
                final article = articleList[index];
                return buildRecommendWidget(context, article);
              },
            )),
      ],
    );
  }

  // 信息块元素
  Widget buildRecommendWidget(BuildContext context, article) {
    return GestureDetector(
      onTap: () {
        Map<String, dynamic> articleData = {
          'id': article['id'],
        };
        // print(articleData);
        // Navigator.pushNamed(context, "/createArticle");

        Navigator.pushNamed(context, "/articleDetail",
            arguments: {"articleId": article['id']});
      },
      child: Container(
          margin: const EdgeInsets.fromLTRB(10, 5, 10, 10),
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height * 0.45,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Container(
                child: ListTile(
                  leading: Card(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadiusDirectional.circular(10)),
                    clipBehavior: Clip.antiAlias,
                    child: Image.network(
                      'http://q2.qlogo.cn/headimg_dl?dst_uin=1019383856&spec=100',
                      width: 40,
                      height: 40,
                      fit: BoxFit.cover,
                    ),
                  ),
                  title: Text("${article["belong"]}"),
                  subtitle: Text("关注 639.2W 帖子 11.5KW"),
                ),
              ),
              Container(
                padding: EdgeInsets.only(left: 10),
                width: MediaQuery.of(context).size.width,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Text(
                      "${article["title"]}",
                      textAlign: TextAlign.left,
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "${article["article_context"]}",
                      textAlign: TextAlign.left,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                 
                    )
                  ],
                ),
              ),
              Container(
                  padding: EdgeInsets.only(left: 10),
                  width: MediaQuery.of(context).size.width,
                  child: Wrap(
                    // mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      buildImageCard("https://via.placeholder.com/150"),
                      buildImageCard("https://via.placeholder.com/150"),
                    ],
                  )),
              Container(
                  padding: EdgeInsets.all(10),
                  width: MediaQuery.of(context).size.width,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      buildRowIconButton(refreshArticleList,
                          Icon(Icons.share, color: Colors.black), "分享"),
                      buildRowIconButton(
                          refreshArticleList,
                          Icon(
                            Icons.message,
                            color: Colors.black,
                          ),
                          "评论"),
                      buildRowIconButton(
                          refreshArticleList,
                          Icon(Icons.star_purple500_outlined,
                              color: Colors.black),
                          "收藏"),
                    ],
                  )),
            ],
          ),
          decoration: BoxDecoration(boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.5),
              spreadRadius: 3,
              blurRadius: 7,
              offset: Offset(0, 3), // changes position of shadow
            ),
          ], color: Colors.white, borderRadius: BorderRadius.circular((20)))),
    );
  }

  // 图片文字
  Widget buildRowIconButton(Function func, Icon icon, String text) {
    return TextButton.icon(
      onPressed: () {
        func();
      },
      icon: icon,
      label: Text(
        text,
        style: TextStyle(color: Colors.black),
      ),
    );
  }

  // 圆角图片卡片
  Widget buildImageCard(String imgUrl) {
    return Card(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadiusDirectional.circular(10)),
      clipBehavior: Clip.antiAlias,
      child: Image.network(
        imgUrl,
        width: 120,
        height: 120,
        fit: BoxFit.cover,
      ),
    );
  }
}
